package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传与回显
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    String path;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {

        // 1.获取到原始文件名
        String filename = file.getOriginalFilename();

        // 2.重构文件名，文件名要唯一
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String subFilename = filename.substring(filename.lastIndexOf("."));
        filename = uuid + subFilename;

        // 3.存储文件的路径
        File dest = new File(path, filename);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        // 4.上传
        file.transferTo(dest);

        //5.响应
        return R.success(filename);
    }

    /**
     * 图片回显
     * @param response
     * @param name
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response,String name) throws IOException {
        // 定位原始文件
        File file = new File(path, name);

        // 构建文件输入流
        FileInputStream fis = new FileInputStream(file);

        // 获取输出流
        ServletOutputStream os = response.getOutputStream();

        // 表示写的是一个图片
        response.setContentType("image/jpeg");

        // 读写操作
        int len;
        byte[] bytes = new byte[1024];

        while ((len = fis.read(bytes)) != -1){
            os.write(bytes,0,len);
            os.flush();
        }

        // 释放资源
        fis.close();
    }

}